<template><div></div></template>
<script>
import { mapState } from 'vuex'
import Login from '@/api/login'
import LoginMixin from '../mixins/login'
export default {
  mixins: [LoginMixin],
  data() {
    return {
      appid: 'wwf4b48c1fe75cc421',
      tokenUrl: '',
      code: ''
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  beforeCreate() {
    this.$toast.loading({
      message: '加载中...',
      duration: 0,
      overlay: true
    })
  },
  created() {
    // if (this.user.token) {
    //   this.$toast.clear()
    //   // 有登录状态，直接进入页面
    //   if (this.user.gridPersonType === '5') {
    //     this.$router.push('/cockpit/home')
    //   } else {
    //     this.$router.push('/home')
    //   }
    // } else {
    // 获取企业微信授权
    this.getCode()
    // }
  },
  methods: {
    getCode() {
      this.code = this.$route.query.code
      this.tokenUrl = window.location.href
      if (this.code) {
        // 已获取到授权，登录
        this.authLogin()
      } else {
        // 获取授权
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
          this.appid
        }&redirect_uri=${encodeURIComponent(
          this.tokenUrl
        )}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`
      }
    },
    authLogin() {
      Login.Login.authLogin({
        code: this.code
      })
        .then(res => {
          this.$toast.clear()
          const { data, status, message } = res.data
          if (status === 0) {
            data.WeChatCode = this.code
            this.setData(data)
            this.getRegionCode()
          } else {
            this.retry(message)
          }
        })
        .catch(() => {
          this.$toast.clear()
          this.retry()
        })
    },
    retry(message = '授权登录失败！') {
      this.$dialog
        .alert({
          title: '提示',
          message: message
        })
        .then(() => {
          this.$router.push('/login')
        })
    }
  }
}
</script>
